#include "threadPool.h"

int mmapSendFile(const char *filename, int netfd, off_t offset)
{   
    //初始化小火车 length data[1024]
    train_t t;
    bzero(&t, sizeof(t));
    //如果文件大小大于100M

    //虚拟映射内存
    int fd = open(filename, O_RDONLY);
    ERROR_CHECK(fd, -1, "open");

    struct stat statbuf;
    int ret = fstat(fd, &statbuf);

    char *p = (char *)mmap(NULL, statbuf.st_size, PROT_READ, MAP_SHARED, fd, 0);
    ERROR_CHECK(p, (void *)-1, "mmap");

    //发送给客户端 
    //send(netfd, p + offset, statbuf.st_size - offset, 0);
    //分批传输给客户端

    while( offset < statbuf.st_size)
    {
        if(statbuf.st_size - offset > sizeof(t.data))
        {
            t.length = sizeof(t.data);
        }
        else
        {
            t.length = statbuf.st_size - offset;
        }

        memcpy(t.data, p + offset, t.length);
        offset += t.length;

        int ret = send(netfd, &t, sizeof(int) + t.length, MSG_NOSIGNAL);
        if(ret == -1)
        {
            printf("send error\n");
            return -1;
        }
    }
    printf("发送成功\n");
    //发送结束标志
    t.length = 0;
    send(netfd, &t, 4,MSG_NOSIGNAL);
    munmap(p, statbuf.st_size);
    close(fd);

    return 0;
}
